//
//  UserViewController.m
//  project
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "UserViewController.h"
#import "LoginViewController.h"
#import "SettingModel.h"
#import "UserTableViewCell.h"
#import "LoggedOutViewController.h"
#import <SDImageCache.h>
#import "LikeViewController.h"
#import "UserOpinionViewController.h"
#import "UserAboutViewController.h"
#import <UIButton+WebCache.h>
#import "StragryLikeViewController.h"
@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UIAlertViewDelegate>
@property (nonatomic, strong)UIButton *userButton;
@property (nonatomic, strong)UILabel *nameLabel;
@property (nonatomic, strong)UIImageView *imgView;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UIScrollView *mainScrollView;
@property (nonatomic, strong)UILabel *cacheLabel;

@end

@implementation UserViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _cacheLabel.text = [NSString stringWithFormat:@"%.2fM",[UserViewController folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]]];
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"] isEqualToString:@""]) {
        _nameLabel.text = @"登录";
    }
    else
    {
        _nameLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"];
    }
    if(![[NSFileManager defaultManager] fileExistsAtPath:[[NSUserDefaults standardUserDefaults]valueForKey:@"file"]]) //如果不存在
{
    if ([[NSUserDefaults standardUserDefaults]valueForKey:@"avatar_url"]!=nil &&(!([[[NSUserDefaults standardUserDefaults]valueForKey:@"avatar_url"]isEqualToString:@""]))) {
        [_userButton sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]valueForKey:@"avatar_url"]] forState:UIControlStateNormal];
    }
    else{
        [_userButton setImage:[UIImage imageNamed:@"user-1"] forState:UIControlStateNormal];}
        }
    else
    {
        NSLog(@"%@",[[NSUserDefaults standardUserDefaults]valueForKey:@"file"]);
        [_userButton setImage:[UIImage imageNamed:[[NSUserDefaults standardUserDefaults]valueForKey:@"file"]] forState:UIControlStateNormal];
    }
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationController.navigationBar.hidden = YES;
    
//    self.view.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 40)];
    _mainScrollView.contentSize = CGSizeMake(kWidth, kHeight+60);
    _mainScrollView.showsVerticalScrollIndicator = NO;
    _mainScrollView.delegate = self;
    [self.view addSubview:_mainScrollView];
    [self addHeaderView];
    _dataArray = [NSMutableArray array];
    [self configData];

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 240, kWidth, 350)];
    
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [_tableView registerClass:[UserTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.rowHeight = 50;
    //_mainScrollView.frame = CGRectMake(0, 20, kWidth, 240 +_tableView.contentSize.height);

    [self.mainScrollView addSubview:_tableView];
}

-(void)configData
{
    SettingModel *model1 = [[SettingModel alloc]initWith:@"liwu" title:@"我喜欢的礼物" color:[[UIColor alloc]initWithRed:252/255.0 green:157/255.0 blue:154/255.0 alpha:1]];
    
    [self.dataArray addObject:model1];
    SettingModel *model2 = [[SettingModel alloc]initWith:@"shoucang" title:@"我喜欢的攻略" color: [[UIColor alloc]initWithRed:179/255.0 green:214/255.0 blue:110/255.0 alpha:1]];
   
    [self.dataArray addObject:model2];
    
    SettingModel *model3 = [[SettingModel alloc]initWith:@"yejianmoshi" title:@"夜间模式" color: [[UIColor alloc]initWithRed:139/255.0 green:101/255.0 blue:8/255.0 alpha:1]];
    [self.dataArray addObject:model3];
    
    SettingModel *model4 = [[SettingModel alloc]initWith:@"qingchuyuhuancun" title:@"清除缓存" color: [[UIColor alloc]initWithRed:255/255.0 green:69/255.0 blue:0/255.0 alpha:1]];
    [self.dataArray addObject:model4];
    
    SettingModel *model5= [[SettingModel alloc]initWith:@"pingfen" title:@"给我们评分吧" color: [[UIColor alloc]initWithRed:127/255.0 green:255/255.0 blue:212/255.0 alpha:1]];
    [self.dataArray addObject:model5];
    
    SettingModel *model6 = [[SettingModel alloc]initWith:@"fankui" title:@"意见反馈" color: [[UIColor alloc]initWithRed:255/255.0 green:227/255.0 blue:132/255.0 alpha:1]];
    [self.dataArray addObject:model6];
    
    SettingModel *model7 = [[SettingModel alloc]initWith:@"guanyu" title:@"关于我们" color:[UIColor greenColor]];
    [self.dataArray addObject:model7];
}

-(void)addHeaderView
{
    _imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"background.jpg"]];
    _imgView.frame = CGRectMake(0, 0, kWidth, 240);

    [self.mainScrollView addSubview:_imgView];
    _imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(login:)];
    [_imgView addGestureRecognizer:singleTap];
    
    _userButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _userButton.frame = CGRectMake((kWidth - 100)/2 , 70, 100, 100);
    if ([[NSUserDefaults standardUserDefaults]valueForKey:@"avatar_url"]!=nil) {
        [_userButton sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]valueForKey:@"avatar_url"]] forState:UIControlStateNormal];
    }
    else{
        [_userButton setImage:[UIImage imageNamed:@"user-1"] forState:UIControlStateNormal];}
    _userButton.backgroundColor = [UIColor whiteColor];
    _userButton.layer.masksToBounds = YES;
    _userButton.layer.cornerRadius = 50;
    [_userButton addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [_imgView addSubview:_userButton];
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 180, (kWidth - 80), 30)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.textColor = [UIColor whiteColor];
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"] isEqualToString:@""]) {
        _nameLabel.text = @"登录";
    }
    else
    {
        _nameLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"];
    }
    
    [_imgView addSubview:_nameLabel];

    
}



-(void)login:(UIButton *)button
{
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"LoginId"]isEqualToString:@""]||([[NSUserDefaults standardUserDefaults]valueForKey:@"LoginId"] == nil)) {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController *loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:loginNC animated:YES completion:nil];
    }
    else
    {
        LoggedOutViewController *loggedOutVC = [[LoggedOutViewController alloc]init];
        UINavigationController *loggedOutNC = [[UINavigationController alloc]initWithRootViewController:loggedOutVC];
        [self presentViewController:loggedOutNC animated:YES completion:nil];
    }

    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat change = -20 -scrollView.contentOffset.y;
    NSLog(@"%f",change);
    if (change > 0) {
        _imgView.frame = CGRectMake(-change,-change-20, kWidth + change*2, 240 +change);
        _userButton.frame = CGRectMake((kWidth - 100)/2 +change, 70+change/2, 100, 100);
//        _userButton.frame = CGRectMake((kWidth - 100)/2 +change/4*3 , 70+change/4, 100 +change/2 , 100+change/2 );
//        _userButton.imageView.frame = CGRectMake(0, 0, 100 +change/2 , 100 +change/2 );
//        _userButton.layer.cornerRadius = 50 +change/4;
        _nameLabel.frame = CGRectMake(40 +change, 180 +change/2, (kWidth - 80), 30);
    }
    else
    {
        _userButton.frame = CGRectMake((kWidth - 100)/2, 70+change/2, 100, 100);
        _nameLabel.frame = CGRectMake(40 , 180 +change/2, (kWidth - 80), 30);
    }
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
            
            
        case 0:
        {
            LikeViewController *likeVC = [[LikeViewController alloc]init];
            [self.navigationController pushViewController:likeVC animated:YES];

        }
              break;
            
        case 1:
        {
            StragryLikeViewController *stragryVC = [[StragryLikeViewController alloc]init];
            [self.navigationController pushViewController:stragryVC animated:YES];
            
        }
            break;
        case 2:
        {
            NSLog(@"夜间模式");
            
        }
            break;
            
        case 3:
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"清除缓存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
           
        }
            break;
        case 4:
        {
            NSLog(@"评分");
        }
            break;
            
        case 5:
        {
            UserOpinionViewController *userOpinionVC = [[UserOpinionViewController alloc]init];
            [self.navigationController pushViewController:userOpinionVC animated:nil];
        }
            break;
        case 6:
        {
            UserAboutViewController *userAboutVC = [[UserAboutViewController alloc]init];
            [self.navigationController pushViewController:userAboutVC animated:nil];
        }
            break;
            
        default:
            break;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == 2)
    {
        UISwitch *ss = [[UISwitch alloc]initWithFrame:CGRectMake(kWidth - 70, 10, 60, 20)];
        [cell addSubview:ss];
        [ss addTarget:self action:@selector(drak:) forControlEvents:UIControlEventValueChanged];
    }
    else if (indexPath.row == 3)
    {
        _cacheLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth - 80, 10, 70, 20)];
        _cacheLabel.text = [NSString stringWithFormat:@"%.2fM",[UserViewController folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]]];
        [cell addSubview:_cacheLabel];
    }
 //   cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.selectionStyle = NO;
    SettingModel *model = self.dataArray[indexPath.row];
    [cell configModel:model];
    
    return cell;
}

-(void)dark:(UISwitch *)seitch
{
    NSLog(@"切换模式");
}

+(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

//计算缓存
+(float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            folderSize +=[UserViewController fileSizeAtPath:absolutePath];
        }//SDWebImage框架自身计算缓存的实现
        folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        if (folderSize < 0) {
            folderSize = 0;
        }
        return folderSize;
    }
    return 0;
}
//清楚缓存
+(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0)
{
    if(buttonIndex == 1)
    {
        [UserViewController clearCache:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
        _cacheLabel.text = [NSString stringWithFormat:@"%.2fM",[UserViewController folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
